<template>
  <el-dialog
    title="选择转办人员"
    v-model="visibleDialog"
    :width="600"
    append-to-body
    class="transfer-user-selector"
  >
    <div class="selector-body">
      <div class="selector-left">
        <input
          type="text"
          placeholder="搜索成员"
          v-model="searchVal"
          @input="handleSearch"
          class="search-input"
        />
        <el-tabs v-model="activeName" @tab-change="handleTabChange">
          <el-tab-pane label="组织架构" name="1"></el-tab-pane>
          <el-tab-pane label="角色列表" name="2"></el-tab-pane>
        </el-tabs>
        <p class="breadcrumb" v-if="activeName === '1' && !searchVal">
          <span @click="loadDepartments(0)" class="breadcrumb-item">刷新</span>
          <span
            v-for="(item, index) in breadcrumbPath"
            class="breadcrumb-item"
            :key="index"
            @click="loadDepartments(item.id)"
            >{{ item.departmentName }}</span
          >
        </p>
        <div class="list-container">
          <div v-if="activeName === '1'" class="department-list">
            <!-- 部门列表 -->
            <div
              v-for="dept in departments"
              :key="dept.id"
              class="list-item department-item"
              :class="{ active: isDepartmentSelected(dept) }"
              @click="toggleDepartment(dept)"
            >
              <span class="item-name">{{ dept.departmentName }}</span>
              <el-button
                v-if="dept.hasChildren"
                link
                size="small"
                @click.stop="loadDepartments(dept.id)"
              >
                进入
              </el-button>
            </div>
            <!-- 员工列表 -->
            <div
              v-for="emp in employees"
              :key="emp.id"
              class="list-item employee-item"
              :class="{ active: isEmployeeSelected(emp) }"
              @click="toggleEmployee(emp)"
            >
              <span class="item-name">{{ emp.employeeName }}</span>
            </div>
          </div>
          <div v-else class="role-list">
            <!-- 角色列表 -->
            <div
              v-for="role in roles"
              :key="role.roleId"
              class="list-item role-item"
              :class="{ active: isRoleSelected(role) }"
              @click="toggleRole(role)"
            >
              <span class="item-name">{{ role.roleName }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="selector-right">
        <div class="selected-header">
          <span>已选择 ({{ totalSelected }})</span>
          <el-button link size="small" @click="clearAll">清空</el-button>
        </div>
        <div class="selected-list">
          <!-- 已选择的角色 -->
          <div v-if="selectedRoles.length > 0" class="selected-section">
            <div class="section-title">角色</div>
            <div
              v-for="role in selectedRoles"
              :key="'role-' + role.roleId"
              class="selected-item"
            >
              <span>{{ role.roleName }}</span>
              <el-button
                link
                size="small"
                @click="removeRole(role)"
                class="remove-btn"
              >
                ×
              </el-button>
            </div>
          </div>
          <!-- 已选择的员工 -->
          <div v-if="selectedEmployees.length > 0" class="selected-section">
            <div class="section-title">员工</div>
            <div
              v-for="emp in selectedEmployees"
              :key="'emp-' + emp.id"
              class="selected-item"
            >
              <span>{{ emp.employeeName }}</span>
              <el-button
                link
                size="small"
                @click="removeEmployee(emp)"
                class="remove-btn"
              >
                ×
              </el-button>
            </div>
          </div>
          <!-- 已选择的部门 -->
          <div v-if="selectedDepartments.length > 0" class="selected-section">
            <div class="section-title">部门</div>
            <div
              v-for="dept in selectedDepartments"
              :key="'dept-' + dept.id"
              class="selected-item"
            >
              <span>{{ dept.departmentName }}</span>
              <el-button
                link
                size="small"
                @click="removeDepartment(dept)"
                class="remove-btn"
              >
                ×
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { workflowApi } from '/@/api/workflow/flowDesigner'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: () => [],
  },
})

const emits = defineEmits(['update:visible', 'change'])

// 响应式数据
const searchVal = ref('')
const activeName = ref('1')
const departments = ref([])
const employees = ref([])
const roles = ref([])
const breadcrumbPath = ref([])
const selectedRoles = ref([])
const selectedEmployees = ref([])
const selectedDepartments = ref([])
const loading = ref(false)

// API实例
const api = workflowApi()

// 计算属性
const visibleDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val)
  },
})

const totalSelected = computed(() => {
  return selectedRoles.value.length + selectedEmployees.value.length + selectedDepartments.value.length
})

// 方法
const loadDepartments = async (parentId = 0) => {
  try {
    loading.value = true
    const response = await api.getDepartments({ parentId })
    if (response.data) {
      departments.value = response.data.childDepartments || []
      employees.value = response.data.employees || []
      breadcrumbPath.value = response.data.titleDepartments || []
    }
  } catch (error) {
    console.error('加载部门数据失败:', error)
    ElMessage.error('加载部门数据失败')
  } finally {
    loading.value = false
  }
}

const loadRoles = async () => {
  try {
    loading.value = true
    const response = await api.getRoles()
    if (response.data && response.data.list) {
      roles.value = response.data.list
    }
  } catch (error) {
    console.error('加载角色数据失败:', error)
    ElMessage.error('加载角色数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = async () => {
  if (!searchVal.value.trim()) {
    if (activeName.value === '1') {
      await loadDepartments()
    } else {
      await loadRoles()
    }
    return
  }

  try {
    loading.value = true
    const searchData = {
      searchName: searchVal.value,
      page: 1,
      size: 30
    }

    if (activeName.value === '1') {
      const response = await api.getEmployees(searchData)
      if (response.data && response.data.list) {
        departments.value = []
        employees.value = response.data.list
      }
    } else {
      const response = await api.getRoles(searchData)
      if (response.data && response.data.list) {
        roles.value = response.data.list
      }
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

const handleTabChange = () => {
  searchVal.value = ''
  if (activeName.value === '1') {
    loadDepartments()
  } else {
    loadRoles()
  }
}

// 选择相关方法
const isDepartmentSelected = (dept) => {
  return selectedDepartments.value.some(item => item.id === dept.id)
}

const isEmployeeSelected = (emp) => {
  return selectedEmployees.value.some(item => item.id === emp.id)
}

const isRoleSelected = (role) => {
  return selectedRoles.value.some(item => item.roleId === role.roleId)
}

const toggleDepartment = (dept) => {
  const index = selectedDepartments.value.findIndex(item => item.id === dept.id)
  if (index > -1) {
    selectedDepartments.value.splice(index, 1)
  } else {
    selectedDepartments.value.push(dept)
  }
}

const toggleEmployee = (emp) => {
  const index = selectedEmployees.value.findIndex(item => item.id === emp.id)
  if (index > -1) {
    selectedEmployees.value.splice(index, 1)
  } else {
    selectedEmployees.value.push(emp)
  }
}

const toggleRole = (role) => {
  const index = selectedRoles.value.findIndex(item => item.roleId === role.roleId)
  if (index > -1) {
    selectedRoles.value.splice(index, 1)
  } else {
    selectedRoles.value.push(role)
  }
}

const removeRole = (role) => {
  const index = selectedRoles.value.findIndex(item => item.roleId === role.roleId)
  if (index > -1) {
    selectedRoles.value.splice(index, 1)
  }
}

const removeEmployee = (emp) => {
  const index = selectedEmployees.value.findIndex(item => item.id === emp.id)
  if (index > -1) {
    selectedEmployees.value.splice(index, 1)
  }
}

const removeDepartment = (dept) => {
  const index = selectedDepartments.value.findIndex(item => item.id === dept.id)
  if (index > -1) {
    selectedDepartments.value.splice(index, 1)
  }
}

const clearAll = () => {
  selectedRoles.value = []
  selectedEmployees.value = []
  selectedDepartments.value = []
}

const confirmSelection = () => {
  const result = [
    ...selectedRoles.value.map(item => ({
      type: 2,
      targetId: item.roleId,
      name: item.roleName,
    })),
    ...selectedEmployees.value.map(item => ({
      type: 1,
      targetId: item.id,
      name: item.employeeName,
    })),
    ...selectedDepartments.value.map(item => ({
      type: 3,
      targetId: item.id,
      name: item.departmentName,
    })),
  ]
  emits('change', result)
}

const closeDialog = () => {
  emits('update:visible', false)
}

// 监听props.data变化，初始化选中状态
watch(
  () => props.data,
  (newData) => {
    if (newData && newData.length > 0) {
      selectedEmployees.value = newData
        .filter(item => item.type === 1)
        .map(({ name, targetId }) => ({
          employeeName: name,
          id: targetId,
        }))
      selectedRoles.value = newData
        .filter(item => item.type === 2)
        .map(({ name, targetId }) => ({
          roleName: name,
          roleId: targetId,
        }))
      selectedDepartments.value = newData
        .filter(item => item.type === 3)
        .map(({ name, targetId }) => ({
          departmentName: name,
          id: targetId,
        }))
    } else {
      clearAll()
    }
  },
  { immediate: true }
)

// 监听弹窗显示状态
watch(
  () => props.visible,
  (val) => {
    if (val) {
      activeName.value = '1'
      searchVal.value = ''
      loadDepartments()
    }
  }
)
</script>

<style scoped>
.transfer-user-selector {
  .selector-body {
    display: flex;
    height: 400px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }

  .selector-left {
    flex: 1;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
  }

  .selector-right {
    width: 200px;
    display: flex;
    flex-direction: column;
  }

  .search-input {
    width: 100%;
    padding: 8px 12px;
    border: none;
    border-bottom: 1px solid #e4e7ed;
    outline: none;
    font-size: 14px;
  }

  .breadcrumb {
    padding: 8px 12px;
    margin: 0;
    font-size: 12px;
    color: #606266;
    border-bottom: 1px solid #e4e7ed;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .breadcrumb-item {
    cursor: pointer;
    color: #409eff;
    margin-right: 8px;
  }

  .breadcrumb-item:hover {
    text-decoration: underline;
  }

  .list-container {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  }

  .list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    margin-bottom: 4px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
  }

  .list-item:hover {
    background-color: #f5f7fa;
  }

  .list-item.active {
    background-color: #e6f7ff;
    border: 1px solid #409eff;
  }

  .item-name {
    flex: 1;
    font-size: 14px;
    color: #303133;
  }

  .selected-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    border-bottom: 1px solid #e4e7ed;
    font-size: 14px;
    font-weight: 500;
  }

  .selected-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  }

  .selected-section {
    margin-bottom: 16px;
  }

  .section-title {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .selected-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 8px;
    margin-bottom: 4px;
    background-color: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
    font-size: 12px;
  }

  .remove-btn {
    color: #f56c6c;
    font-size: 16px;
    padding: 0;
    min-height: auto;
    line-height: 1;
  }

  .remove-btn:hover {
    color: #f56c6c;
    background-color: transparent;
  }
}

:deep(.el-tabs__header) {
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 12px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

/* 清空按钮样式 */
:deep(.el-button.is-link) {
  padding: 2px 8px;
  background-color: #f6f8fa;
  border: 1px solid #d0d7de;
  border-radius: 4px;
  color: #656d76;
  font-size: 12px;
  transition: all 0.2s ease;
}

:deep(.el-button.is-link:hover) {
  background-color: #f3f4f6;
  border-color: #8c959f;
  color: #24292f;
  transform: translateY(-1px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-button.is-link:active) {
  transform: translateY(0);
  box-shadow: 0 0 0 rgba(0, 0, 0, 0.1);
}
</style>